angular.module('unique-directive', []).directive('userUnique', ['UserService', function(UserService) {
	return {
		restrict : 'A',
		scope : true,
		require : 'ngModel',
		link : function(scope, elem, attrs, ngModel) {
			if (!ngModel)
				return;

			//elem.unbind('input').unbind('keydown').unbind('change');
			
			elem.bind('focus', function(e) {
				scope.$apply(function() {
					if (!ngModel || !elem.val())
						return;

					ngModel.$setValidity("user-unique", true);
				});
			});

			elem.bind('blur', function(e) {
				scope.$apply(function() {
					if (!ngModel || !elem.val())
						return;
					
					var exclusived = '';
					var keyProperty = scope.$eval(attrs.userUnique);
					if(keyProperty == undefined) {
						keyProperty = attrs.userUnique
					}
					
					var key = keyProperty;
					if(typeof keyProperty === 'object'){
						key = keyProperty['name'];
						exclusived = keyProperty['exclusived'];
					}  
					
					var currentValue = elem.val();
					
					if(currentValue === exclusived) {
						ngModel.$setValidity("user-unique", true);
						return;
					}
	                
	                UserService.isExistedUser(key, currentValue).then(function(existed){
	                	if (currentValue == elem.val()) { 
	                		ngModel.$setValidity("user-unique", (existed === "false"));
	                	}
	                });

					
				});

			});
		}
	};
} ]);